<?php
declare (strict_types = 1);

namespace app\index\controller;

// use think\Request;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Config;
use app\middleware\Auth;

class User{
    protected $middleware = [Auth::class];
    //获取用户收藏展品
    public function getCollectExhibits(){
        if(Request::isPost()){
            $accountId=input('param.accountId',0);
            $openId=input('param.openId','');
            $page=input('param.page',1);
            $size=input('param.size',10);
            $data=Db::table('account_collection ac')
            ->field('e.title,e.cover,e.id,e.era,e.tex,e.customize_code')
            ->join('exhibits e','ac.exhibit_id=e.id')
            ->where(['ac.open_id'=>$openId,'ac.is_cannel'=>0])
            ->order('ac.create_time desc')
            ->paginate([
                    'list_rows' => $size,
                    'page'      => $page
                ]);
    
            $total=$data->total();
            $data=$data->items();
            $page_count=ceil($total/$size);
            foreach($data as $k=>$v){
                $cover=json_decode($v['cover'],true);
                $data[$k]['cover']=isset($cover[0])?'https://darong.storage.1415926.com.cn'.$cover[0]:'https://uviewui.com/swiper/swiper1.png';
            }
            $result=['code'=>200,'message'=>'获取成功','success'=>true,'result'=>['list'=>$data,'total'=>$total,'page'=>['current'=>$page,'size'=>$size,'total'=>$page_count]]];
            return json($result);
        }
    }

      //获取小程序openid
    public function loginByXcx(){
        if(Request::isPost()){ 
            $code =input('param.code'); // 这里假设code是通过POST方式传输的
            // 发送请求给微信服务器，换取openid和session_key
            $wx= Config::get('wx');
            $appid = $wx['mini']['appId'];
            $secret = $wx['mini']['secret'];
            // $appid='wx8917abbb073757ba';
            // $secret='2fbb0a8747777abdf4b4961afe06adc6';
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
            $response = file_get_contents($url);
            $data = json_decode($response, true);
            $account_id=Db::table('account')->where(['openid'=>$data['openid']])->value('account_id');
            $time=time();
            if($account_id){
                $update=['last_login_time'=>$time];
                if(isset($data['unionid'])){
                    $update['unionid']=$data['unionid'];
                }
                Db::table('account')->where(['openid'=>$data['openid']])->update($update);
            }else{
                $insert=[
                    'openid'=> $data['openid'],
                    'nickname'=>'用户'.substr($data['openid'], -4),
                    'create_time'=> $time
                ];
                if(isset($data['unionid'])){
                    $insert['unionid']=$data['unionid'];
                }
                $account_id=Db::table('account')->insertGetId($insert);
            }
            Db::table('account_login_log')->insertGetId([
                'account_id'=>$account_id,
                'openid'=>$data['openid'],
                'create_at'=>$time
            ]);
            
            $data['id']=$account_id;
            return json(['code'=>200,'success'=>true,'message'=>'登录成功','result'=>$data]);  
        }
    }
    
    public function setAccountNickName(){
        if(Request::isPost()){
            try{
                $accountId=input('param.accountId',0);
                $openId=input('param.openid','');
                $nickname=input('param.nickname',"");
                if($openId==""&&$nickname==""&&$accountId==0){
                    return json(['code'=>200,'success'=>false,'message'=>'参数出错']);  
                }

                Db::table('account')->where(['openid'=>$openId,'account_id'=>$accountId])
                ->update(['nickname'=>$nickname]);
                return json(['code'=>200,'success'=>true,'message'=>'设置成功']);  

            }catch (Exception $e) {
                return json(['code'=>200,'success'=>false,'message'=>$e]);
            }
        }
    }

     public function setAccountAvatar(){
        if(Request::isPost()){
            $file = request()->file();
            try{
                $accountId=input('param.accountId',0);
                $openId=input('param.openid','');
                if($openId==""&&$accountId==0){
                    return json(['code'=>200,'success'=>false,'message'=>'参数出错']);  
                }
                validate(['image'=>'fileSize:2097152|fileExt:jpg,png,jpeg'])->check($file);

                $avatar = request()->file('avatar');
                $savename =\think\facade\Filesystem::disk('toStorageUrl')->putFile( 'avatar', $avatar);
                Db::table('account')->where(['openid'=>$openId,'account_id'=>$accountId])
                ->update(['avatar'=>$savename]);
                return json(['code'=>200,'success'=>true,'message'=>'设置成功','result'=>['url'=>'https://darong.storage.1415926.com.cn/'.$savename]]);  

           } catch (\think\exception\ValidateException $e) {
                return json(['code'=>200,'success'=>false,'message'=>$e->getMessage()]);
            }
        }
    }
    
    public function menu(){
        if(Request::isPost()){
            $openId=input('param.openid','');

            $result=[];
            $result['account']=Db::table('account')->field('avatar,nickname')->where(['openid'=>$openId])->find();
            $result['account']['avatar']=$result['account']['avatar']?'https://darong.storage.1415926.com.cn/'.$result['account']['avatar']:'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
            $result['menu']=[
				// ['icon'=>'setting-fill','title'=>'我的成员','url'=>'/pages/user/member','isLink'=>true],
				['icon'=>'coupon-fill','title'=>'我的预约','url'=>'/pages/user/apply/list','isLink'=>true],
				// ['icon'=>'tags-fill','title'=>'我的兑换','url'=>'','isLink'=>true],
                ['icon'=>'bookmark-fill','title'=>'我的收藏','url'=>'/pages/user/collect_exhibit','isLink'=>true]
            ];
            return json(['code'=>200,'success'=>true,'message'=>'设置成功','result'=>$result]);  
        }
    }

    public function getPhoneNumber(){
        if(Request::isPost()){
            $code=input('param.code','');
            if($code==""){
                return json(['code'=>200,'success'=>false,'message'=>'参数出错']);  
            }
            $access_token=getAccessToken();
            $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$access_token}";
            $postData = json_encode(['code' => $code]);
            $header=['Content-Type: application/json'];
            $info=json_decode(curlHeaderRequest($url,$postData, $header,'POST'),true);
            $success=$info['errcode']==0?true:false;
            $message=$success?'获取成功':$info['errmsg'];
            $reslut=$success?$info['phone_info']:[];
            $openId=input('param.openId','');
            if($openId!=''&&$info['errcode']==0){
                Db::table('account')->where(['openid'=>$openId])->update(['mobile'=>$info['phone_info']['phoneNumber']]);
            }
            return json(['code'=>200,'success'=>$success,'message'=>$message,'result'=>$reslut]);
        }
    }
}